package com.aiit.controller;

import com.aiit.mapper.UserMapper;
import com.aiit.pojo.User;
import com.aiit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;


/**
 * Created with IntelliJ IDEA.
 *
 * @Author: LuTao
 * @Date: 2022/04/28/14:16
 */
@Slf4j
@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/logincheck",method = RequestMethod.POST)
    public String login(String username, String password, HttpSession session, Model model){
        try {
            Subject subject = SecurityUtils.getSubject();
            System.out.println(subject);
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            subject.login(usernamePasswordToken);
             session.setAttribute("loginUser",username);
            if (subject.isAuthenticated()) {
//                logger.debug("是否拥有角色:" + subject.hasRole("reader"));
                System.out.println(subject.hasRole("systemadmin"));
                return "redirect:/index.html";
            }
        }catch (
             UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("msg","用户名错误");
            System.out.println("用户名错误");
         } catch (
            IncorrectCredentialsException e) {
            e.printStackTrace();
            model.addAttribute("msg","密码错误");
            System.out.println("密码错误");
          }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
          }
       return "/login";
      }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }
      @RequestMapping(value = "register02")
         public String register(User user){
           userService.register(user);
           return "redirect:/login";
      }
}
